﻿using CIS.DB;
using CIS.Web.Common;
using CIS.Web.Models;
using CIS.Web.Properties;
using ClassHmac2003;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Linq.Dynamic;
using System.Threading.Tasks;
using System.Web.Mvc;

namespace CIS.Web.Controllers
{
	[RoutePrefix("ProfileConferenceAttendPay")]
	public class ProfileConferenceAttendPayController : BaseDbController
	{
		public ActionResult Index()
		{
			string controller = RouteData.Values["controller"].ToString();
			string actionName = RouteData.Values["action"].ToString();
			Utility.InsertLog(LoginUser, Request.Url.ToString(), controller, actionName);

			return View();
		}

		public async Task<JsonCamelCaseResult> GetData(int? page, int? rows, string sort, string order, ProfileConferenceAttendPayModel model)
		{
			int take = rows ?? ConstValues.DefaultGridRows;
			int skip = ((page ?? 1) - 1) * take;

			var conferenceAttendenceInfo = DbContext.ConferenceAttendenceInfo.AsNoTracking()
					.Where(x => x.Creator == LoginUser.UserName)
					.Join(DbContext.ConferenceMaster.AsNoTracking(),
						info => info.ConferenceId,
						master => master.ID,
						(info, master) => new
						{
							Id = info.ID,
							ConferenceName = master.ConferenceName,
							Currency = info.Currency,
							TotalFee = info.TotalFee,
							Discount = info.Discount,
							HasPaid = info.HasPaid,
							Creator = info.Creator,
							ConferenceId = info.ConferenceId,
							PayStartDate = master.PayStartDate,
							PayEndDate = master.PayEndDate,
							ConferenceNickName = master.ConferenceNickName,
							BenefitEndDate = master.BenefitEndDate,
							BenefitStartDate = master.BenefitStartDate,
							HomePageUrl = master.HomePageUrl,
							PaymentTypeId = info.PaymentTypeId,
							FullName = info.FullName,
							IsInternational = master.IsInternational,
						});

			var sql = DbContext.ProfilePaymentInfo.AsNoTracking()
					.Where(x => x.UserName == LoginUser.UserName)
				    .GroupBy(x => new { x.AttendenceId })
				    .Select(x => new
				    {
					    AttendenceId = x.Key.AttendenceId,
					    CreateDate = x.Max(e => e.CreateDate)
				    })
				    .Join(conferenceAttendenceInfo,
					pay => pay.AttendenceId,
					info => info.Id,
					(pay, info) => new
					{
						Id = info.Id,
						ConferenceName = info.ConferenceName,
						Currency = info.Currency,
						TotalFee = info.TotalFee,
						Discount = info.Discount,
						HasPaid = info.HasPaid,
						CreateDate = pay.CreateDate,
						ConferenceId = info.ConferenceId,
						Creator = info.Creator,
						PayStartDate = info.PayStartDate,
						PayEndDate = info.PayEndDate,
						ConferenceNickName = info.ConferenceNickName,
						BenefitEndDate = info.BenefitEndDate,
						BenefitStartDate = info.BenefitStartDate,
						HomePageUrl = info.HomePageUrl,
						PaymentTypeId = info.PaymentTypeId,
						FullName = info.FullName,
						IsInternational = info.IsInternational
					});

			if (!string.IsNullOrWhiteSpace(model.queryConferenceName) && model.queryConferenceName != "")
			{
				sql = sql.Where(x => x.ConferenceName.Contains(model.queryConferenceName));
			}
			if (!string.IsNullOrWhiteSpace(model.queryHasPaid) && model.queryHasPaid != "")
			{
				var paidSql = model.queryHasPaid == ConstValues.PaidStatus.已缴费 ? true : false;
				sql = sql.Where(x => x.HasPaid == paidSql);
			}

			int total = await sql.CountAsync();
			if (!string.IsNullOrEmpty(sort))
			{
				sql = sql.OrderBy(sort + ConstValues.chrSpace + order).Skip(skip).Take(take);
			}
			else
			{
				sql = sql.OrderByDescending(x => x.CreateDate).Skip(skip).Take(take);
			}

			var sqlResult = await sql.ToListAsync();

			var result = sqlResult.Select(x => new
			{
				Id = x.Id,
				ConferenceName = x.ConferenceName,
				Currency = x.Currency,
				TotalFee = x.BenefitStartDate < DateTime.Now && DateTime.Now < x.BenefitEndDate ? x.Discount.Value.ToString("N2") : x.TotalFee.Value.ToString("N2"),
				HasPaid = x.HasPaid,
				CreateDate = !x.IsInternational ? x.CreateDate.Value.ToString("yyyy-MM-dd") : x.CreateDate.Value.ToString("MM/dd/yyyy"),
				ConferenceId = x.ConferenceId,
				Creator = x.Creator,
				PayStartDate = x.PayStartDate.Value.ToString("yyyy-MM-dd"),
				PayEndDate = x.PayEndDate.Value.ToString("yyyy-MM-dd"),
				ConferenceNickName = x.ConferenceNickName,
				HomePageUrl = x.HomePageUrl,
				PaymentTypeId = DbContext.ConferencePaymentMaster.AsNoTracking().FirstOrDefault(y => y.ID == x.PaymentTypeId)?.PayId,
				//PayName = DbContext.SysPaymentMaster.AsNoTracking().FirstOrDefault(y => y.ID == x.PaymentTypeId)?.PaymentName,
				FullName = x.FullName,
				IsInternational = x.IsInternational
			});

			var result2 = result.Select(x => new
			{
				Id = x.Id,
				ConferenceName = x.ConferenceName,
				Currency = x.Currency,
				TotalFee = x.TotalFee,
				HasPaid = x.HasPaid,
				CreateDate = x.CreateDate,
				ConferenceId = x.ConferenceId,
				Creator = x.Creator,
				PayStartDate = x.PayStartDate,
				PayEndDate = x.PayEndDate,
				ConferenceNickName = x.ConferenceNickName,
				HomePageUrl = x.HomePageUrl,
				//PaymentTypeId = DbContext.ConferencePaymentMaster.AsNoTracking().FirstOrDefault(y => y.ID == x.PaymentTypeId)?.PayId,
				PayName = x.IsInternational ?
							DbContext.SysPaymentMaster.AsNoTracking().FirstOrDefault(y => y.ID == x.PaymentTypeId)?.PaymentNameEn :
							DbContext.SysPaymentMaster.AsNoTracking().FirstOrDefault(y => y.ID == x.PaymentTypeId)?.PaymentName,
				FullName = x.FullName,
				IsInternational = x.IsInternational,
				payLanguage = x.IsInternational ? ConstValues.Language.En : ConstValues.Language.Cn,
			});

			return JsonCamelCase(new
			{
				Total = total,
				Rows = result2,
			},
			JsonRequestBehavior.AllowGet);
		}

		[Route("GetPaymentInfoData/{id}")]
		public async Task<JsonCamelCaseResult> GetPaymentInfoData(string id)
		{
			var sql = from paymentInfo in DbContext.ProfilePaymentInfo.AsNoTracking()
					.Where(x => x.AttendenceId == id)
				  join attInfo in DbContext.ConferenceAttendenceInfo.AsNoTracking()
					on paymentInfo.AttendenceId equals attInfo.ID
				  join conferenceMaster in DbContext.ConferenceMaster.AsNoTracking()
					on attInfo.ConferenceId equals conferenceMaster.ID
				  orderby paymentInfo.FeeType
				  select new ProfilePayInfoModel
				  {
					  FeeType = paymentInfo.FeeType,
					  FeeId = paymentInfo.FeeId,
					  FeeName = string.Empty,
					  Count = paymentInfo.Count,
					  Currency = paymentInfo.Currency,
					  Fee = paymentInfo.Fee,
					  Discount = paymentInfo.Discount,
					  BenefitEndDate = conferenceMaster.BenefitEndDate,
					  BenefitStartDate = conferenceMaster.BenefitStartDate,
					  ConferenceId = conferenceMaster.ID,
					  DisplayName = ""
				  };

			int total = await sql.CountAsync();
			var sqlResult = await sql.ToListAsync();

			double? conferenceFee = 0.00;
			double? eventFee = 0.00;
			string totalCurrency = "";
			sqlResult.ForEach(x =>
			{
				if (x.FeeType == ConstValues.FeeType.餐费)
				{
					x.DisplayName = DbContext.ConferenceAttendenceForm.AsNoTracking().FirstOrDefault(y => y.ConferenceId == x.ConferenceId && y.Key == "Meal")?.DisplayName;
					double? Fee = x.BenefitStartDate < DateTime.Now && DateTime.Now < x.BenefitEndDate ? x.Discount : x.Fee;
					conferenceFee += Fee;
					x.FeeName = DbContext.FeeMealMaster.AsNoTracking().FirstOrDefault(y => y.ID == x.FeeId).FeeName;
					totalCurrency = x.Currency;
				}
				else if (x.FeeType == ConstValues.FeeType.参会费)
				{
					x.DisplayName = DbContext.ConferenceAttendenceForm.AsNoTracking().FirstOrDefault(y => y.ConferenceId == x.ConferenceId && y.Key == "Attendence")?.DisplayName;
					double? Fee = x.BenefitStartDate < DateTime.Now && DateTime.Now < x.BenefitEndDate ? x.Discount : x.Fee;
					conferenceFee += Fee;
					x.FeeName = DbContext.FeeAttendenceMaster.AsNoTracking().FirstOrDefault(y => y.ID == x.FeeId).RegisterType;
					totalCurrency = x.Currency;
				}
				else if (x.FeeType == ConstValues.FeeType.版面费)
				{
					x.DisplayName = DbContext.ConferenceAttendenceForm.AsNoTracking().FirstOrDefault(y => y.ConferenceId == x.ConferenceId && y.Key == "Page")?.DisplayName;
					double? Fee = x.BenefitStartDate < DateTime.Now && DateTime.Now < x.BenefitEndDate ? x.Discount : x.Fee;
					conferenceFee += Fee;
					x.FeeName = DbContext.FeePageMaster.AsNoTracking().FirstOrDefault(y => y.ID == x.FeeId).FeeName;
					totalCurrency = x.Currency;
				}
				else if (x.FeeType == ConstValues.FeeType.其他费用)
				{
					x.DisplayName = DbContext.ConferenceAttendenceForm.AsNoTracking().FirstOrDefault(y => y.ConferenceId == x.ConferenceId && y.Key == "Other")?.DisplayName;
					double? Fee = x.BenefitStartDate < DateTime.Now && DateTime.Now < x.BenefitEndDate ? x.Discount : x.Fee;
					conferenceFee += Fee;
					x.FeeName = DbContext.FeeOtherMaster.AsNoTracking().FirstOrDefault(y => y.ID == x.FeeId).FeeName;
					totalCurrency = x.Currency;
				}
				else if (x.FeeType == ConstValues.FeeType.同期活动费)
				{
					x.DisplayName = DbContext.ConferenceAttendenceForm.AsNoTracking().FirstOrDefault(y => y.ConferenceId == x.ConferenceId && y.Key == "ConcurrentEvent")?.DisplayName;
					var ConcurrentEventId = DbContext.FeeConcurrentEventMaster.AsNoTracking().FirstOrDefault(y => y.ID == x.FeeId)?.ConcurrentEventId;
					x.FeeName = DbContext.ConcurrentEventMaster.AsNoTracking().FirstOrDefault(y => y.ID == ConcurrentEventId)?.EventName;
					double? Fee = x.BenefitStartDate < DateTime.Now && DateTime.Now < x.BenefitEndDate ? x.Discount : x.Fee;
					eventFee += Fee;
					totalCurrency = x.Currency;
				}
			});

			var result = sqlResult.Select((x, index) => new
			{
				Number = index + 1,
				Currency = x.Currency,
				Name = x.DisplayName + ConstValues.chrSpace + ConstValues.chrComma + ConstValues.chrSpace + x.FeeName,
				Fee = x.BenefitStartDate < DateTime.Now && DateTime.Now < x.BenefitEndDate ? x.Discount : x.Fee,
			});

			return JsonCamelCase(new
			{
				Total = total,
				Rows = result,
			},
			JsonRequestBehavior.AllowGet);
		}
	}
}